import axios from 'axios';
import global from '@/components/common/httpurl.vue'
import route from '../router/index'

const service = axios.create({
    // baseURL:'http://localhost:8080',//本地解决跨域
    // baseURL: global.httpUrl, //服务器
    baseURL: process.env.VUE_APP_BASE_API, //服务器

    // baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 200000
});
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
service.interceptors.request.use(
    config => {
        let token = localStorage.getItem('token')
        if (window.location.host.indexOf('192.168') > -1 || window.location.host.indexOf('localhost') > -1) {
            //判断是内网地址的话，就请求内网后端接口地址
            config.baseURL = process.env.VUE_APP_BASE_API;
            console.log('1', config.baseURL)
            // let token = '123'
            if (token) {
                config.headers['token'] = token || ''
            }
        } else {
            //判断是外网地址的话，就请求外网后端接口地址
            config.baseURL = process.env.VUE_APP_BASE_API_WWW;
            console.log('2', config.baseURL)
            // let token = '123'
            if (token) {
                config.headers['token'] = token || ''
            }
        }
        return config
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            console.log('response', response)
            if (response.data.code === 401) {
                localStorage.clear()
                this.$message.error(response.data.message)
                route.replace({
                    path: "/login"
                });
            } else {
                return response.data;
            }
        } else {
            Promise.reject();
        }
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

function downloadFile(url = '', methods = 'get', data = {}, params = {}, fileTitle = '', type = 'excel') {
    service({
        url: url,
        method: methods,
        data: data,
        params: params,
        responseType: 'blob'
    }).then((res) => {
        console.log('filedowload', res)
        if (objectTool.isObject(res.data)) {
            message.error(res.data.message)
            return
        }
        const name = fileTitle || res.config.params.fileTile
        if ('download' in document.createElement('a')) {
            const blob = new Blob([res.data], {
                type: type
            })
            // const blob = res.data
            const link = document.createElement('a')
            const url = window.URL.createObjectURL(blob)
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', name)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        } else {
            navigator.msSaveBlob(res.data, name)
        }
    })
}

function numberToChinese(num) {
    var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var cnIntRadice = ['', '拾', '佰', '仟'];
    var cnIntUnits = ['', '万', '亿', '兆'];
    var cnDecUnits = ['角', '分', '毫', '厘'];
    var cnInteger = '整';
    var cnIntLast = '元';
    var maxNum = 999999999999999.9999;
    var integerNum,
        decimalNum,
        chineseStr = '';
    var parts;

    if (num === '') {
        return '';
    }
    num = parseFloat(num);
    if (num >= maxNum) {
        return '';
    }
    if (isNaN(num)) {
        return '';
    }
    if (num === 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
    }
    num = num.toString();
    if (num.indexOf('.') === -1) {
        integerNum = num;
        decimalNum = '';
    } else {
        parts = num.split('.');
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
    }

    if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
            var n = integerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n === '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    chineseStr += cnNums[0];
                }
                zeroCount = 0;
                chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m === 0 && zeroCount < 4) {
                chineseStr += cnIntUnits[q];
            }
        }
        chineseStr += cnIntLast;
    }
    if (decimalNum !== '') {
        var decLen = decimalNum.length;
        for (var j = 0; j < decLen; j++) {
            var m = decimalNum.substr(j, 1);
            if (m !== '0') {
                chineseStr += cnNums[Number(m)] + cnDecUnits[j];
            }
        }
    }
    if (chineseStr === '') {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (decimalNum === '') {
        chineseStr += cnInteger;
    }

    // 处理 "一十" 的情况
    // chineseStr = chineseStr.replace('壹拾', '拾');
    // 处理 "零拾" 的情况
    chineseStr = chineseStr.replace('零拾', '零');
    // 去除多余的 "零"
    while (chineseStr.indexOf('零零') !== -1) {
        chineseStr = chineseStr.replace('零零', '零');
    }
    // 去除连续的 "零"，保留一个
    chineseStr = chineseStr.replace(/(零)\1+/g, '零');
    // 去除结尾的 "零"
    chineseStr = chineseStr.replace(/(零)+$/, '');

    return chineseStr;
}
export default service;
export {
    downloadFile,
    numberToChinese
}